﻿using System;
using System.Collections.Generic;
using System.IO;
using System.IO.IsolatedStorage;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Media.Imaging;
using Assistant;
using ICSharpCode.SharpZipLib.GZip;

/**
 * 创建时间：2014/10/12 18:14:59
 * 作者：yong.blackcore
 * Email：itblackhole@outlook.com
 * QQ：50404503
 */
namespace YoucaiReader.Helper
{
    public class DownloadBookFile
    {
        public List<string> DownloadImageList = new List<string>();

        public List<string> DownloadUriList = new List<string>();

        public List<string> IdList = new List<string>();

        public bool currentState;

        public WebClient client;

        private WebClient imageClient;

        public DownloadBookFile()
        {
            if (SettingHelper.IsSettings("DownloadUriList"))
            {
                this.DownloadUriList = SettingHelper.GetValueFromSettings("DownloadUriList") as List<string>;
                this.IdList = SettingHelper.GetValueFromSettings("IdList") as List<string>;
                this.DownloadImageList = SettingHelper.GetValueFromSettings("DownloadImageList") as List<string>;
            }
        }

        public void AddDownloadImage(string imageUri)
        {
            this.DownloadImageList.Add(imageUri);
            SettingHelper.SaveInToSettings("DownloadImageList", this.DownloadImageList);
        }

        public void AddDownloadList(string bookUri, string id)
        {
            this.IdList.Add(id);
            this.DownloadUriList.Add(bookUri);
            SettingHelper.SaveInToSettings("DownloadUriList", this.DownloadUriList);
            SettingHelper.SaveInToSettings("IdList", this.IdList);
        }

        public void BeginDownload()
        {
            if (!this.currentState && this.GetListCount() > 0)
            {
                this.currentState = true;
                this.client = new WebClient()
                {
                    Headers = GetHttpInfoHelper.GetHttpHeaders()
                };
                this.client.OpenReadCompleted += new OpenReadCompletedEventHandler(this.webClient_OpenReadCompleted);
                this.client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(this.webClient_DownloadProgressChanged);
                this.client.OpenReadAsync(new Uri(this.DownloadUriList[0]));
                int localBookListIndex1 = this.GetLocalBookListIndex(this.IdList[0]);
                if (localBookListIndex1 == -1)
                {
                    return;
                }
                else
                {
                    App.LocalBook.T_LocalBookListViewModel()[localBookListIndex1].int_IsDownload_M = 1;
                }                
            }
        }

        public void DeleteDownloadClient()
        {
            this.client.DownloadProgressChanged -= new DownloadProgressChangedEventHandler(this.webClient_DownloadProgressChanged);
            this.client.OpenReadCompleted -= new OpenReadCompletedEventHandler(this.webClient_OpenReadCompleted);
            this.client.CancelAsync();
            this.client = null;
            this.DownloadUriList.RemoveAt(0);
            this.IdList.RemoveAt(0);
            this.currentState = false;
            SettingHelper.SaveInToSettings("DownloadUriList", this.DownloadUriList);
            SettingHelper.SaveInToSettings("IdList", this.IdList);
        }

        public void DeleteDownloadImage()
        {
            this.DownloadImageList.RemoveAt(0);
            SettingHelper.SaveInToSettings("DownloadImageList", this.DownloadImageList);
        }

        public void DeleteDownloadImageClient()
        {
            this.imageClient.OpenReadCompleted -= new OpenReadCompletedEventHandler(this.imageClient_OpenReadCompleted);
            this.imageClient.CancelAsync();
            this.imageClient = null;
            this.DownloadImageList.RemoveAt(0);
            SettingHelper.SaveInToSettings("DownloadImageList", this.DownloadImageList);
        }

        public void DeleteDownloadList(string bookUri, string id)
        {
            this.IdList.Remove(id);
            this.DownloadUriList.Remove(bookUri);
            SettingHelper.SaveInToSettings("DownloadUriList", this.DownloadUriList);
            SettingHelper.SaveInToSettings("IdList", this.IdList);
        }

        public void DownloadImage()
        {
            if (this.DownloadImageList.Count > 0)
            {
                this.imageClient = new WebClient();
                this.imageClient.OpenReadCompleted += new OpenReadCompletedEventHandler(this.imageClient_OpenReadCompleted);
                this.imageClient.OpenReadAsync(new Uri(this.DownloadImageList[0]));
            }
        }

        public int GetListCount()
        {
            return this.DownloadUriList.Count;
        }

        public int GetLocalBookListIndex(string id)
        {
            for (int i = 0; i < App.LocalBook.T_LocalBookListViewModel().Count;i++)
            {
                if (App.LocalBook.T_LocalBookListViewModel()[i].str_Id_M == id)
                {
                    return i;
                }
            }
            return -1;
        }

        public void imageClient_OpenReadCompleted(object s, OpenReadCompletedEventArgs e)
        {
            try
            {
                if (e.Result != null)
                {
                    string absolutePath = (new Uri(this.DownloadImageList[0])).AbsolutePath;
                    char[] chrArray = new char[] { '/' };
                    string str = string.Concat("/Shared/ShellContent/", absolutePath.TrimStart(chrArray).Replace('/', '\u005F'));
                    BitmapImage bitmapImage = new BitmapImage();
                    IsolatedStorageFileStream isolatedStorageFileStream = IsolatedStorageFile.GetUserStoreForApplication().OpenFile(str, FileMode.Create, FileAccess.ReadWrite);
                    bitmapImage.SetSource(e.Result);
                    WriteableBitmap writeableBitmap = new WriteableBitmap(bitmapImage);
                    Extensions.SaveJpeg(writeableBitmap, isolatedStorageFileStream, 173, 230, 0, 100);
                    isolatedStorageFileStream.Flush();
                    isolatedStorageFileStream.Close();
                }
                else
                {
                    this.DeleteDownloadImageClient();
                }
                this.DeleteDownloadImageClient();
            }
            catch (WebException webException)
            {
                if (webException.Status != WebExceptionStatus.RequestCanceled)
                {
                    this.DeleteDownloadImageClient();
                }
                else
                {
                    this.imageClient.OpenReadCompleted -= new OpenReadCompletedEventHandler(this.imageClient_OpenReadCompleted);
                    this.imageClient.CancelAsync();
                    this.imageClient = null;
                }
            }
        }

        public bool IsDownloadList(string id)
        {
            if (this.IdList.IndexOf(id) >= 0)
            {
                return true;
            }
            return false;
        }

        public void RemoveTemporaryProgress()
        {
            if (this.IdList.Count > 0)
            {
                int localBookListIndex = this.GetLocalBookListIndex(this.IdList[0]);
                if (-1 == localBookListIndex)
                {                    
                    return;
                }
                App.LocalBook.T_LocalBookListViewModel()[localBookListIndex].int_ProgressValue_M = 0;
            }
        }

        public void webClient_DownloadProgressChanged(object s, DownloadProgressChangedEventArgs e)
        {
            int localBookListIndex = this.GetLocalBookListIndex(this.IdList[0]);
            if (-1 != localBookListIndex)
            {
                Deployment.Current.Dispatcher.BeginInvoke(() => App.LocalBook.T_LocalBookListViewModel()[localBookListIndex].int_ProgressValue_M = 187 * e.ProgressPercentage / 100);
                return;
            }          
        }

        public void webClient_OpenReadCompleted(object s, OpenReadCompletedEventArgs e)
        {
            try
            {
                if (e.Result != null)
                {
                    Stream gZipInputStream = new GZipInputStream(e.Result);
                    IsolatedStorageFileStream isolatedStorageFileStream = App.QQReader_StorageFile.StorageFile.OpenFile(this.IdList[0], FileMode.Create, FileAccess.ReadWrite);
                    byte[] numArray = new byte[2048];
                    int num = 0;
                    while (true)
                    {
                        num = gZipInputStream.Read(numArray, 0, (int)numArray.Length);
                        if (num == 0)
                        {
                            break;
                        }
                        isolatedStorageFileStream.Write(numArray, 0, num);
                    }
                    isolatedStorageFileStream.Flush();
                    isolatedStorageFileStream.Close();
                    int localBookListIndex = this.GetLocalBookListIndex(this.IdList[0]);
                    if (localBookListIndex != -1)
                    {
                        App.LocalBook.T_LocalBookListViewModel()[localBookListIndex].int_IsDownload_M = 2;
                    }                    
                    this.DeleteDownloadClient();
                }
                else
                {
                    this.DeleteDownloadClient();
                    Prompt.PromptMessage("提示：书籍下载失败！");
                }
            }
            catch (WebException webException)
            {
                if (webException.Status != WebExceptionStatus.RequestCanceled)
                {
                    this.DeleteDownloadClient();
                    Prompt.PromptMessage("提示：书籍下载失败！");
                }
                else
                {
                    this.client.DownloadProgressChanged -= new DownloadProgressChangedEventHandler(this.webClient_DownloadProgressChanged);
                    this.client.OpenReadCompleted -= new OpenReadCompletedEventHandler(this.webClient_OpenReadCompleted);
                    this.client.CancelAsync();
                    this.client = null;
                    this.currentState = false;
                }
            }
        }
    }
}
